package org.ithang;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

public class GenWord {

	public static void genWord(Order order) {
		try {
			System.out.println(order);
			String tempPath=GenBoostrap.getCurrentDir();
			
	        String templatePath = tempPath+"/temp.docx";
	        String outputPath = tempPath+"/orders\\";
	        
	        outputPath=System.getProperty("user.home") + "\\Desktop\\orders\\";
	        
	        
	        //log.info("currentDir={}",templatePath);
	        	        
	        File dir=new File(outputPath);
	        if(!dir.exists()) {
	        	dir.mkdir();
	        }
	        
	        InputStream inputStream = FileUtils.openInputStream(new File(templatePath));// new FileInputStream(templatePath);
	        XWPFDocument document = new XWPFDocument(inputStream);

	        Map<String, Object> hashMap = new HashMap<>();
	        
	        Field[] fields=Order.class.getDeclaredFields();
	        
	        //String fileName=null;
	        String title=null;
	        for(Field field:fields) {
	        	String key=field.getName();
	        	field.setAccessible(true);
	        	Object obj=field.get(order);
	        	if("title".equals(key)) {
	        		title=String.valueOf(obj);
	        		if(title.startsWith("黑色气")) {
	        			String[] ss=title.split(" ");
		        		hashMap.put("{title}", ss[0]);
		        		hashMap.put("{height}", ss.length>1?ss[1]:"");
		        		hashMap.put("wid", ss.length>2?ss[2]:"");
		        		hashMap.put("{info}","重量："+ss[1]+" 宽："+ss[2].replaceFirst("宽", ""));
		        		hashMap.put("{anum}", order.getNum()+"个");
	        		}else {
	        			String[] ss=title.split(" ");
		        		hashMap.put("{title}", ss[0]);
		        		if(ss.length>1) {
		        			hashMap.put("{info}",ss[1]+"  48卷/箱");
		        		}else {
		        			hashMap.put("{info}",ss[0]+"  48卷/箱");
		        		}
		        		hashMap.put("{anum}", (order.getNum()/48)+"箱");
		        		//System.out.println("途虎................."+(order.getNum()/48)+"="+order.getNum());
	        		}
	        		
	        	}else {
	        		if("toAddress".equals(key)) {
	        			//fileName=obj+"_"+title.split(" ")[0]+"2.docx";
	        			outputPath+=obj+"_"+title.split(" ")[0]+".docx";
	        		}
	        		if("number".equals(key)) {
	        			hashMap.put("numb", null==obj?"":obj);
	        		}
	        		hashMap.put("{"+key+"}", null==obj?"":obj);
	        	}
	        	
	        }
	        LocalDate dat=LocalDate.now();
	        
	        //生产日期
	        hashMap.put("{curDate}", dat.getYear()+"年"+dat.getMonthValue()+"月"+dat.getDayOfMonth()+"号");
	        //hashMap.put("{curDate}", dat.getYear()+"年01月23日");
	        
	        LocalDate ndat=dat.plusDays(7);
	        
	        //发货日期
	        hashMap.put("{verifyDate}", ndat.getYear()+"年"+ndat.getMonthValue()+"月"+ndat.getDayOfMonth()+"日");
	        //hashMap.put("{verifyDate}", "");
	        // 替换占位符
	        replacePlaceholdersInDocument(document, hashMap);
	        System.out.println(hashMap);

	       System.out.println("生成文档:"+outputPath);
	       File file=new File(outputPath);
	       int i=2;
	       
	       
	       while(file.exists()) {
	    	   StringBuilder sber=new StringBuilder(file.getAbsolutePath());
	    	   sber.insert(sber.indexOf("docx")-1, String.valueOf(i++));
	    	   file.renameTo(new File(sber.toString()));
	       }
	       file.createNewFile();
	        // 保存生成的文档
	        FileOutputStream outputStream = new FileOutputStream(outputPath);
	        document.write(outputStream);
	        outputStream.close();

	        //log.info("生成:{}",fileName);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	private static void replacePlaceholdersInDocument(XWPFDocument document, Map<String, Object> hashMap) {
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            replaceParagraphPlaceholders(paragraph, hashMap);
        }

        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        replaceParagraphPlaceholders(paragraph, hashMap);
                    }
                }
            }
        }
    }
	
	private static void replaceParagraphPlaceholders(XWPFParagraph paragraph,Map<String, Object> values) {
		values.forEach((k,v)->{
			
			for (XWPFRun r : paragraph.getRuns()) {
	              String text = r.getText(0);
	              if (text != null && text.contains(k)) {
	                text = text.replace(k, String.valueOf(v));
	                r.setText(text,0);
	              }
	            }
			
		});
	}
	
}
